<template>
  <div class="box-order-status-wrapper app-container">
    <div class="box-order-content">
      <el-row class="mb8 mt10" :gutter="10">
        <el-col :span="1.5">
          <div class="flex-one large-tip bolder-font">{{ $t('common.BoxDetails') }}</div>
        </el-col>
      </el-row>
      <!-- 按钮组 -->
      <el-row class="mb8 mt10" :gutter="10">
        <!-- 仓库库位容器 -->
        <!-- 出库不要容器 入库要容器  -->
        <el-form label-width="110px" :model="warehouseForm" ref="warehouseForm" :rules="rules" :inline="true" label-position="left" style="margin-top: 10px;">
          <div v-if="fromType === 'IN'">
            <el-form-item :label="$t('common.selectWare')" prop="warehouseId">
              <WmsAreaCascader v-model="warehouseForm.warehouseId" size="small"></WmsAreaCascader>
            </el-form-item>
            <el-form-item :label="$t('common.container')" prop="rackId">
              <el-select v-model="warehouseForm.rackId" :placeholder="$t('common.placeholderSelect')" @focus="getContainerId">
                <el-option v-for="item in ContainerOptions" :key="item.id" :label="item.rackName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <!-- 操作按钮 -->
        <!-- 左侧 -->
        <el-col :span="1.5" style="float: left;">
          <el-input
            v-model="boxCode"
            prefix-icon="el-icon-search"
            :placeholder="$t('common.pleaseBOXCODEType')"
            style="margin-right: 10px"
            @change="searchBoxCode"
            clearable
          />
        </el-col>
        <el-col :span="1.5" style="float: left;">
          <el-button type="primary" :disabled="finish" @click="beforeSubmitForm(1)">{{ $t("common.save") }}</el-button>
          <el-button type="danger" @click="beforeSubmitForm(2)">{{ $t("common.abnormal") }}</el-button>
        </el-col>
        <!-- 右侧 -->
        <el-col :span="1.5" style="float: right;">
          <el-button type="info" @click="selectNone">{{ $t("common.removeAll") }}</el-button>
          <el-button type="cancel" @click="handleAbnormal">{{ $t("common.cancel") }}</el-button>
        </el-col>
        <el-col :span="1.5" style="float: right;">
          <el-input
            v-model="boxCodeRight"
            prefix-icon="el-icon-search"
            :placeholder="$t('common.pleaseBOXCODEType')"
            style="margin-right: 10px"
            clearable
          />
        </el-col>
      </el-row>
      <div class="table">
        <el-form ref="form" :model="form" :show-message="false"></el-form>
        <div class="table-box">
          <div class="table-box-left">
            <BoxListComponent
              ref="boxList"
              :allList="checkbox"
              :checkbox="checkbox"
              :value="leftFixedBoxes"
              :is-sku="false"
              :cancel-value="boxCode || boxCodeRight"
              @selection-change="handleSelectionBoxChange"
            />
          </div>
          <div class="table-box-right" style="margin-top: 31px">
            <BoxListComponent
              ref="boxList2"
              :is-sku="false"
              :value="form.details"
              :cancel-value="boxCodeRight"
              :is-pagination="false"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog :title="$t('common.pleaseInput')" :visible.sync="beforeVisible" width="40%">
      <el-form :inline="true">
        <el-form-item prop="abnormalCause" label="请填写异常原因：">
          <el-input v-model="abnormalCause" clearable placeholder="异常原因"
        /></el-form-item>
      </el-form>
      <BoxListComponent
        ref="boxList3"
        :is-sku="false"
        :value="unselectedBoxes"
        :is-reason="true"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeVisible = false">{{
          $t("common.cancel")
        }}</el-button>
        <el-button type="danger" @click="submitForm">{{
          "异常保存"
        }}</el-button>
        <el-button type="primary" @click="submitInwarehouseForm"
          >{{ "异常" }}<span>{{ fromType === "IN" ? "入" : "出" }}</span
          >{{ "库" }}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request.js";
// 入库
import { updateBox } from "@/api/wms/receiptOrder";
// 出库
import { addOrUpdateWmsShipmentOrder } from "@/api/wms/shipmentOrder";
import BoxListComponent from "@/views/components/wms/BoxList/index.vue";
import WmsAreaCascader from "@/components/WmsAreaCascader";
import { listWmsRack } from "@/api/wms/rack";

export default {
  components: { BoxListComponent, WmsAreaCascader },
  props: {
    // 表格数据
    form: {
      type: Object,
      default: () => {},
    },
    // 箱子默认左侧选择框
    checkbox: {
      type: Boolean,
      default: true,
    },
    // 来源： IN入库 OUT出库
    fromType: {
      type: String,
      default: null,
    },
  },
  watch: {
    form: {
      handler(v) {
        if (v) {
          // 默认左侧全部数据 右侧空数据
          this.leftFixedBoxes = this.form.details;
          // 左侧数据为状态异常的箱子
          // this.form.details.filter(item => item.receiptOrderStatus === 9);
          this.form.details = [];
        }
      },
      immediate: true,
    },
  },
  computed: {},
  data() {
    return {
      finish: false,
      boxCode: null,
      // 右侧输入框
      boxCodeRight: null,
      // 扫码枪扫过的右侧箱子列表
      leftFixedBoxes: [],
      // 未选中箱子dialog
      beforeVisible: false,
      // 未选中的箱子
      unselectedBoxes: [],
      // 异常原因
      abnormalCause: null,
      warehouseForm: {
        warehouseId: null,
        areaId: null,
        rackId: null
      },
      rules: {
        warehouseId: [{ required: true, message: this.$t("common.placeholderSelect"), trigger: "blur" },],
        // rackId: [{ required: true, message: this.$t("common.placeholderSelect"), trigger: "blur" },]
      },
      ContainerOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10000,
        rackNo: null,
        rackName: null,
        areaId: null,
        warehouseId: null,
      },
    };
  },
  methods: {
    beforeSubmitForm(num) {
      // 2031128 以前的逻辑 保存前弹出框填写异常原因
      // const array = this.leftFixedBoxes.filter((item) => {
      //   return !this.form.details.some((box) => box.id === item.id);
      // });
      // this.unselectedBoxes = array;
      // if (this.unselectedBoxes.length) {
      //   this.beforeVisible = true;
      // } else {
      //   this.submitForm(num);
      // }
      // 2031128逻辑 异常和正常的箱子都通过接口保存并刷新页面
      if (num === 1) {
        this.$refs['warehouseForm'].validate((valid) => {
          if (valid) {
            if (this.form.details.length) {
              this.submitForm(num);
            } else {
              this.$message.info(this.$t('common.pleaseaddbox'))
            }
          } 
        })
      } else if (num === 2) {
        if (this.form.details.length) {
          this.unselectedBoxes = this.form.details.map((r) => {
            if(this.fromType === "IN") {
              r.receiptOrderStatus = 9;
            } else {
              r.shipmentOrderStatus = 14;
            }
            return r
          })
          this.beforeVisible = true
          // this.submitForm(num);
        } else {
          this.$message.info(this.$t('common.pleaseaddbox'))
        }
      }
    },
    // 正常保存
    submitForm(num) {
      // 未选中的箱子
      // this.unselectedBoxes
      // 2031128 以前的逻辑 保存前弹出框更改出入库未选中箱子的状态
      // const boxList3 = this.$refs.boxList3 ? this.$refs.boxList3.listData.map((r) => {
      //   if(this.fromType === "IN") {
      //     r.receiptOrderStatus = 9;
      //   } else {
      //     r.shipmentOrderStatus = 14;
      //   }
      //   return r
      // }) : []
      // 所有箱子（包括未选中的）
      // const details = [...this.form.details, ...boxList3];
      // 所有箱子（包括未选中的）
      const details = [...this.form.details];
      const boxList3 = this.$refs.boxList3 ? this.$refs.boxList3.listData : []
      delete this.form.details
      // 参数
      const req = {
        details: num === 2 ? boxList3 : details,
        ...this.form,
        // details: boxList3,
        // 一些箱子的异常原因
        abnormalCause: this.abnormalCause,
      };
      delete req.createTime;
      req.details.map((r) => {
        // r.itemList = r.boxDetailVOS
        // 正常保存
        if (num === 1) {
          if (this.fromType === "IN") {
            r.receiptOrderStatus = 3
            r.warehouseId = this.warehouseForm.warehouseId[0],
            r.areaId = this.warehouseForm.warehouseId[1],
            r.rackId = this.warehouseForm.rackId ? this.warehouseForm.rackId : null
          } else {
            r.shipmentOrderStatus = 13
          }
          r.abnormalStatus = 0
          return r
        }
        // 异常保存
        else if (num === 2) {
          this.fromType === "IN" ? r.receiptOrderStatus = 9 : r.shipmentOrderStatus = 14
          r.abnormalStatus = 1
          return r
        }
        delete r.createTime;
        // delete r.boxDetailVOS;
      });
      const api =
        this.fromType === "IN" ? updateBox : addOrUpdateWmsShipmentOrder;
      // console.log("req", req, api);
      // return;
      api(req).then((response) => {
        if (response.code == 398) {
          return;
        }
        this.$modal.msgSuccess(this.$t('common.succcessInfo'));
        this.clear()
        // this.cancel();
      });
      this.beforeVisible = false;
      // this.cancel();
    },
    // 异常保存
    submitInwarehouseForm() {
      const boxList3 = this.$refs.boxList3 ? this.$refs.boxList3.listData : []
      delete this.form.details
      // 参数
      const req = {
        details: boxList3,
        ...this.form,
        // 一些箱子的异常原因
        abnormalCause: this.abnormalCause,
      };
      delete req.createTime;
      req.details.map((r) => {
        this.fromType === "IN" ? r.receiptOrderStatus = 3 : r.shipmentOrderStatus = 14
        // 异常出入库加这个字段
        r.abnormalStatus = 1
        delete r.createTime;
        return r
      });
      const api =
        this.fromType === "IN" ? updateBox : addOrUpdateWmsShipmentOrder;
      // console.log("req", req, api);
      // return;
      api(req).then((response) => {
        if (response.code == 398) {
          return;
        }
        this.$modal.msgSuccess(this.$t('common.succcessInfo'));
        this.clear()
      });
      this.beforeVisible = false;
    },
    clear() {
      this.form.details = []
      this.$emit('refresh')
      this.$refs['warehouseForm'].resetFields()
    },
    cancel() {
      const path =
        this.fromType === "IN" ? "/wms/receiptOrder" : "/wms/shipmentOrder";
      this.$tab.closeOpenPage({ path: path });
    },
    // 扫码枪
    searchBoxCode() {
      if (this.boxCode) {
        this.getSearchBoxCodeInfo();
      }
    },
    getSearchBoxCodeInfo() {
      const data = {
        boxCode: this.boxCode,
        // shipmentOrderId: this.$route.query.id,
      };
      const api = this.fromType === "IN" ? '/wms/receiptOrder/getInfoByBoxCode' : '/wms/shipmentOrder/getInfoByBoxCode'
      if(this.fromType === "IN") {
        data.receiptOrderId = this.$route.query.id
      } else {
        data.shipmentOrderId = this.$route.query.id
      }
      request.post(api, data).then((r) => {
        var res = r;
        let list = {};
        list = res;
        if (list === "") {
          this.$message.error(this.$t('common.noSearshBoxCodeMsg'));
        } else {
          const found =
            this.form.details.length > 0
              ? this.form.details.find((item) => item.id === list.id)
              : null;
          if (found) {
            this.$message.warning(this.$t('common.changeBoxCodeMsg'));
          } else {
            let listpat = {
              ...list,
              boxDetailVOS: [],
            };
            this.form.details.push(listpat);
          }
          this.$refs.boxList.singleSubmit()
        }
        this.boxCode = null;
      });
    },
    // 选择框筛选
    handleSelectionBoxChange(v) {
      this.form.details = v
      if (v.length === 0) {
        this.form.details = [];
      } else {
        this.chooseList = v.map((r) => {
          // if ((r.check = true)) {
          //   const boxCodeIndex = this.form.details.findIndex(
          //     (item) => item.boxCode === r.boxCode
          //   );
          //   if (boxCodeIndex !== 0 && !this.form.details.includes(r)) {
          //     this.form.details.push(r);
          //   }
          // } else if ((r.check = false)) {
          //   const index = this.form.details.findIndex(
          //     (item) => item.id === r.id
          //   );
          //   if (index !== -1) {
          //     this.form.details.splice(index, 1);
          //   }
          // }
          // 右侧箱子默认设置为出库状态 13
          this.fromType === "IN"
            ? (r.receiptOrderStatus = 3)
            : (r.shipmentOrderStatus = 13);
          return r;
        });
      }
    },
    // 获取容器
    getContainerId() {
      const { pageNum, pageSize } = this.queryParams;
      const query = {
        ...this.queryParams,
        pageNum: undefined,
        pageSize: undefined,
      };
      const pageReq = { page: pageNum - 1, size: pageSize };
      listWmsRack(query, pageReq).then((response) => {
        const { content } = response;
        this.ContainerOptions = content;
      });
    },
    selectNone() {
      this.form.details = []
      this.$refs.boxList.cancelAll()
    },
    handleAbnormal() {
      this.$refs.boxList.singleCancel()
      this.form.details = this.form.details.filter(item => item.boxCode !== this.boxCodeRight);
      // 置空右侧输入框值
      this.boxCodeRight = null
    }
  },
};
</script>

<style lang="stylus">
.box-order-status-wrapper
  .box-order-content
    min-width 900px
    margin 0 auto
.table-box
  display flex
  justify-content space-between
.table-box-left
  width 100%
.table-box-right
  width 100%
</style>
